//
//  SerialSearchResultsViewController.m
//  XPhoto
//
//  Created by baboy on 2019/5/7.
//  Copyright © 2019 baboy. All rights reserved.
//

#import "SerialSearchResultsViewController.h"
#import "Theme.h"
#import "UIButton+x.h"
#import "SerialTableViewCell.h"

@interface SerialSearchResultsViewController ()<UITableViewDelegate, UITableViewDataSource>
@property(nonatomic, strong) NSArray *serials;
@end

@implementation SerialSearchResultsViewController
- (id)init{
    if (self = [super initWithNibName:NSStringFromClass([self class]) bundle:nil]) {
        
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
//    self.extendedLayoutIncludesOpaqueBars = YES;
//    self.definesPresentationContext = YES;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.tableView.tableFooterView = [UIView new];
//    self.navigationController.navigationBar.opaque = NO;
//    self.navigationController.navigationBar.backgroundColor = [UIColor whiteColor];
//    self.tableView.tableHeaderView.backgroundColor = [UIColor blueColor];
    // Do any additional setup after loading the view from its nib.
}
- (void)setKeyword:(NSString *)keyword{
    BOOL isUpdated = NO;
    if (keyword != _keyword || ![keyword isEqualToString:_keyword]) {
        isUpdated = YES;
    }
    _keyword = keyword;
    [self search:keyword];
}
- (void)search:(NSString *)keyword{
    PostSerialSearchArgs *searchArgs = [PostSerialSearchArgs new];
    searchArgs.keyword = keyword;
    [PostSerial search:searchArgs
           withCallback:^(id  _Nonnull task, NSArray*  ret, NSError * _Nullable error) {
               if (error) {
                   return;
               }
               NSMutableArray *serials = [NSMutableArray array];
               if (ret) {
                   [serials addObjectsFromArray:ret];
               }
               BOOL isContainKeyword = NO;
               for (PostSerial *s in serials) {
                   if ([s.title isEqualToString:keyword]) {
                       isContainKeyword = YES;
                       break;
                   }
               }
               if (!isContainKeyword) {
                   PostSerial *newSerial = [PostSerial new];
                   newSerial.title = keyword;
                   [serials insertObject:newSerial atIndex:0];
               }
               self.serials = serials;
               [self.tableView reloadData];
               
           }];
    
    
}
- (void)reload{
    [self.tableView reloadData];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma tableView
- (SerialTableViewCell *)serialTableViewCell{
    SerialTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier: SERIAL_TABLE_VIEW_CELL_REUSE_ID];
    if (!cell) {
        cell = loadViewFromNib([SerialTableViewCell class], self);
    }
    return cell;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSInteger n = self.serials.count;
    return n;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    PostSerial *serial = [self.serials objectAtIndex:indexPath.row];
    if (!serial.id) {
        return 44;
    }
    PostSerial *postSerial = [self.serials objectAtIndex:indexPath.row];
    CGFloat h = [[self serialTableViewCell] heightWithPostSerial:postSerial width:tableView.bounds.size.width];
    return h;
}
- (UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    PostSerial *serial = [self.serials objectAtIndex:indexPath.row];
    if(!serial.id){
        NSString *cellReuseId = @"SerialTableViewCellCreate";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellReuseId];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellReuseId];
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.backgroundColor = THEME_BTN_BG_COLOR;
            btn.contentEdgeInsets = UIEdgeInsetsMake(5, 10, 5, 10);
            btn.titleLabel.font = THEME_TAG_BTN_TITLE_FONT;
            [btn setTitle:NSLocalizedString(@"create", @"标签") forState:UIControlStateNormal];
            [btn sizeToFit];
            btn.layer.cornerRadius = btn.bounds.size.height/2;
            btn.clipsToBounds = YES;
            cell.accessoryView = btn;
            btn.userInteractionEnabled = NO;
        }
        cell.textLabel.text = serial.title;
        cell.detailTextLabel.text = serial.addr?:@"--";
        return cell;
    }
    if(serial.id){
        SerialTableViewCell *cell = [self serialTableViewCell];
        cell.postSerial = serial;
        return cell;
    }
    return nil;
}
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(serialSearchViewController:didSelectSerial:)]) {
        PostSerial *serial = [self.serials objectAtIndex:indexPath.row];
        [self.delegate serialSearchViewController:self didSelectSerial:serial];
    }
}
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath{
    
}
@end
